var express = require('express');
var session = require('express-session');
var path = require('path');
var router = express.Router();
var sqlite3 = require('sqlite3').verbose();

/* GET users listing. */
router.get('/', function (req, res, next) {
  var db = new sqlite3.Database(path.join(__dirname, "../db/data.s3db"));
  var username = req.query.username;
  var mid = req.query.mid;
  var mode2 = req.query.mode2;
  var redata = {};
  if (mode2 == '1') {
    try {
      db.serialize(function () {
        sqlStr = "SELECT * from cart where mid=='" + mid + "' and username=='" + username + "'";
        db.all(sqlStr, function (err, rows) {
          if (rows.length != 0) {
            redata.number = rows[0].number;
            res.send(redata);
          } else
            res.send('0');
        });
      });
    } catch (ex) {
      console.log(ex);
    }
  } else if (mode2 == '2') { //购物车分页显示
    var size = 4;
    var page = req.query.page;
    var num = 0;
    try {
      db.serialize(function () {
        sqlStr = "SELECT * from cart join material on cart.mid=material.mid where username=='" + username + "'";
        db.all(sqlStr, function (err, rows) {
          redata.count = rows.length;
          redata.code = '0';
          redata.data = [];
          if (rows.length <= size)
            redata.data = rows;
          else {
            N = rows.length - size * (page - 1);
            if (N >= size)
              for (i = size * (page - 1); i < size * page; i++) {
                redata.data[num] = rows[i];
                num++;
              }
            else
              for (i = size * (page - 1); i < size * (page - 1) + N; i++) {
                redata.data[num] = rows[i];
                num++;
              }
          }
          res.send(redata);
        });
      });
    } catch (ex) {
      console.log(ex);
    }
  } else if (mode2 == '3') { //购物车删除
    try {
      db.run("DELETE FROM cart WHERE username=='" + username + "' and mid=='" + mid + "'");
      res.send('1');
    } catch (ex) {
      console.log(ex);
    }
  } else if (mode2 == '4') { //确认订单货物详情
    try {
      db.serialize(function () {
        sqlStr = "SELECT * from cart join material on cart.mid=material.mid where cart.mid=='" + mid + "' and username=='" + username + "'";
        db.all(sqlStr, function (err, rows) {
          if (rows.length != 0) {
            redata.data = rows;
            redata.count = rows.length;
            redata.code = '0';
            res.send(redata);
          } else
            res.send('0');
        });
      });
    } catch (ex) {
      console.log(ex);
    }
  }
});

module.exports = router;